/* 
Copyright (c) 2004,2005, 2006, 2007, 2008 University of Illinois 

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

//BIG NOTE: Make sure that formElement.js is included
AccessibilityExtension.ns(function() { with (AccessibilityExtension.LIB) {

	var AE = AccessibilityExtension.ns;  

	var focusableElements = ['form','input','button','textarea','select','option','fieldset','label','legend','map', 'br'];
	
	//The actual <form>
	function formObject(torder,tnode) {
		this.order = torder;
		this.formElements = new Array();
		if (tnode.nodeName && tnode.nodeName == '#document') {
			this.unboundForm = true;
			//accessext_consoleDump("Found the unbound case");
		}
		this.parseNode(tnode);
	}
	
	formObject.prototype = {
		unboundForm : false,//If true, this is the form object that contains all form elements that are not already part of a form
		order : null,
		text : null,
		alt : null,
		node : null,
		titleFound : false,
		missinglabel : false,
		formElements : null,
		display : true,
		displayDetails: null,
		nodeGetText : function(inputNode) {
			var temp = "";
			if(this.node.getAttribute) {
				temp = accessext_getBundleSingleString('forms.formDefaultTitle');
				temp = temp.replace('%s',(this.order).toString()); //accessext_getBundleString did not work for forms 10 and and over
				if (inputNode.hasAttribute("title")) {
					temp = temp.concat(GetValueFromAttributes(inputNode,['title'],""));
					this.titleFound = true;
				} else if (this.node.hasAttribute("alt")) {
					temp = temp.concat(GetValueFromAttributes(inputNode,['alt'],""));
				} 
			}
			return temp;	
		},
		parseNode : function(node) {
			this.formElements = new Array();
			this.node = node;
			if (this.unboundForm) {
				this.text = accessext_getBundleSingleString('forms.nonFormElements');
			} else {
				this.text = this.nodeGetText(this.node);
				this.alt = GetUserAltFromNode(this.node);
			}
			this.parseSubElements();
		},
		getTreeNode : function(windoc) {
			var item= accesxt_generateTreeboxResults(windoc,['order','text']);
			if (!this.titleFound && !this.unboundForm) {
				var row = item.getElementsByTagName('treerow');
				row[0].setAttribute('properties','failRow');
			}
			return item;
		},
		createformElement : function(inputNode) {
			//n = new createFormElementObject(inputNode, this.text);
			n = newFormElementObject(inputNode, this.text);
			n.order = AE.dataarray.length + 1; //		n.order =this.formElements.length + 1;
			this.formElements[this.formElements.length] = n;
			AE.dataarray[AE.dataarray.length] = n;
			if (n.source == 5) { // source_none 
				this.missinglabel = true;
			}		
		},
		nonFocusableElementInForm : function(node) {
			var el;
			function is_focusable()
			{
				if (node.nodeName.toLowerCase() == "a" && typeof node.href != "undefined") return true;
				if (node.hasAttribute('tabindex')) return true;
				if (typeof node.tabindex != "undefined") return true;
				if (focusableElements.indexOf(node.nodeName.toLowerCase()) != -1) return true;
				if (node.nodeName.toLowerCase() == "span" || node.nodeName.toLowerCase() == "div" || node.nodeName.toLowerCase() == "p") {
					if (node.textContent) {
						if (cleanSpaces(node.textContent) == "") {return true;} 
	//					else {alert('textContent' + cleanSpaces(node.textContent))}
					} else { return true; }
				}
				
				return false;
			}
			if (!is_focusable()) {
				return node.nodeName;
			}
			for (node=node.firstChild;node;node=node.nextSibling) if (node.nodeType == 1) {
				el=this.nonFocusableElementInForm(node);
				if (el) {
					return node.nodeName;
				}
			}
			return false;
		},
		parseSubElements : function() {
			var firstFormEleIndex = AE.dataarray.length;				
			var subs = new Array();
			var n = null;
			if (this.unboundForm) {
				subs = getAllFormElementsNotBelongingToForm(this.node);
			} else {
				subs = this.node.elements;
			}			
			//<input type="image" ...> are not picked up by the code below!
			var inputNodes = AE.mydoc.getElementsByTagName("input");
			for (var i = 0; i < inputNodes.length; i ++) {
				var inputType = GetValueFromAttributes(inputNodes[i],['type'],"");
			    if (inputType.toLowerCase() == 'image') {
					var isadded = false;
					var p = inputNodes[i].parentNode;
					while (p != null) {
						if (p.nodeName.toLowerCase() == 'form') {
							if (this.nodeGetText(p) == this.text) { //match it up with the current form if possible
								this.createformElement(inputNodes[i]);
								isadded = true;
								break;
							}
						}
						p = p.parentNode;
					}
					if (isadded == false && this.order == 1) {
						this.createformElement(inputNodes[i]);
					}
				}
			}
			firstFormEleIndex = AE.dataarray.length;	
			for (var i = 0; i < subs.length; i ++) {
				if (subs[i].tagName!='FIELDSET') {
					var inputType = GetValueFromAttributes(subs[i],['type'],"");
				    if (inputType.toLowerCase() != 'hidden') {this.createformElement(subs[i]); }
				}
			}
	/* nonfocusablesibling - finish later
			if (dataarray.length > 0 && dataarray.length > firstFormEleIndex) {
				var nodeName;
				if (nodeName = this.nonFocusableElementInForm(this.node)) {
					while (!dataarray[firstFormEleIndex].display && firstFormEleIndex < dataarray.length) {firstFormEleIndex++;}			
					dataarray[firstFormEleIndex].nonfocusablesibling = true;
				}
			}
	*/
			var strNone = accessext_getBundleSingleString('none');	
			for (var i=0, j=0, n=AE.dataarray.length; i<n; i++) {    
				if (AE.dataarray[i].source == AE.source_none) continue;              
				var effLab1 = AE.dataarray[i].legend.toLowerCase() + ' ' + AE.dataarray[i].label.toLowerCase();          
				for (j=i+1; j<n; j++) {  
					if (AE.dataarray[j].source == AE.source_none) continue;  
					var effLab2 = AE.dataarray[j].legend.toLowerCase() + ' ' + AE.dataarray[j].label.toLowerCase();          
					if (effLab1.indexOf(accessext_getBundleSingleString("forms.noLabel")) == -1 && effLab1==effLab2) {
						AE.dataarray[i].duplicatelabel=AE.dataarray[j].duplicatelabel=true;
						if (AE.dataarray[j].id != strNone && AE.dataarray[i].id==AE.dataarray[j].id) {AE.dataarray[i].duplicateID=AE.dataarray[j].duplicateID=true;}	
					}	
				}
			}
				
			setMaxSeverityForArray(AE.dataarray);
			
		},
		getNoteText : function() {
			var note = '';
			if (!this.titleFound && !this.unboundForm) {
				note = accessext_getBundleSingleString('forms.note.missingTitle') + ' \n';
			}
			if (this.missinglabel) {
				note += accessext_getBundleSingleString('forms.note.missinglabel') + ' \n';
			}
			return note;
		}
	}
	
AccessibilityExtension.LIB.extend(AccessibilityExtension.LIB,
{
	ParseDocumentForForms: function (doc) {
	    try {
			var a = new Array();
			var forms = doc.forms;
			
			for (var i = 0; i < forms.length; i++) {
				var frmObj = new formObject(a.length + 1,forms[i]);
				a[a.length] = frmObj
			}
			
			var unbound = new formObject(a.length,doc);
			if (null != unbound.formElements && unbound.formElements.length > 0) {
				a[a.length] = unbound;
			}
			
			return a;
	    } catch (err) {
	    	accessext_consoleDump("ParseDocumentForForms: ", err);
	    }
	},
	
	parseAndLoadFormObjects: function (doc) {
		var a = new Array();
		
		if (AE.FBcall) { // todo: set AE.thewindow if called from FB, see ParseDocumentForFormElements()
			a = a.concat(ParseDocumentForForms(doc));
			return a;
		} else {
	 		var documents = accessext_getDocuments(AE.thewindow,new Array());
			
			for (var i =0; i < documents.length; i++) {
				a = a.concat(ParseDocumentForForms(documents[i]));
			}
			return a; 
		}
	
	}
});
}});

